//
//  MSCalendarViewController.m
//  Example
//
//  Created by Eric Horacek on 2/26/13.
//  Copyright (c) 2013 Monospace Ltd. All rights reserved.
//

#import "MSCalendarViewController.h"
#import "MSCollectionViewCalendarLayout.h"
#import "MSEvent.h"
// Collection View Reusable Views
#import "MSGridline.h"
#import "MSTimeRowHeaderBackground.h"
#import "MSDayColumnHeaderBackground.h"
#import "MSEventCell.h"
#import "MSDayColumnHeader.h"
#import "MSTimeRowHeader.h"
#import "MSCurrentTimeIndicator.h"
#import "MSCurrentTimeGridline.h"
#import "BiMATRIXCreateEventViewController.h"
#import "BiMATRIXEditEventViewController.h"
#import "BiMATRIXCalendarDataSaver.h"

NSString * const MSEventCellReuseIdentifier = @"MSEventCellReuseIdentifier";
NSString * const MSDayColumnHeaderReuseIdentifier = @"MSDayColumnHeaderReuseIdentifier";
NSString * const MSTimeRowHeaderReuseIdentifier = @"MSTimeRowHeaderReuseIdentifier";

@interface MSCalendarViewController () <MSCollectionViewDelegateCalendarLayout,UIGestureRecognizerDelegate,addEventModelDelegate,PopoverViewDelegate>
{
  //  NSMutableArray* _dataArray;
    NSIndexPath* currentIndexPath;
    UIBarButtonItem* editEventButtonItem;
    UIBarButtonItem* addEventButtonItem;
    NSString* currentSelectedEventTitle;
}
@property (nonatomic, strong) MSCollectionViewCalendarLayout *collectionViewCalendarLayout;

@end

@implementation MSCalendarViewController

- (id)init
{
    self.collectionViewCalendarLayout = [[MSCollectionViewCalendarLayout alloc] init];
    self.collectionViewCalendarLayout.delegate = self;
    self = [super initWithCollectionViewLayout:self.collectionViewCalendarLayout];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(popVc)];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    self.title = @"日程";
    addEventButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"barbuttonicon_add"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(createEvent)];
    self.navigationItem.rightBarButtonItem = addEventButtonItem;
    
    
    editEventButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"edit_n"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(editEvent)];
    
    
    
    self.collectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 20);
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:MSEventCell.class forCellWithReuseIdentifier:MSEventCellReuseIdentifier];
    [self.collectionView registerClass:MSDayColumnHeader.class forSupplementaryViewOfKind:MSCollectionElementKindDayColumnHeader withReuseIdentifier:MSDayColumnHeaderReuseIdentifier];
    [self.collectionView registerClass:MSTimeRowHeader.class forSupplementaryViewOfKind:MSCollectionElementKindTimeRowHeader withReuseIdentifier:MSTimeRowHeaderReuseIdentifier];
    
    // These are optional. If you don't want any of the decoration views, just don't register a class for them.
    [self.collectionViewCalendarLayout registerClass:MSCurrentTimeIndicator.class forDecorationViewOfKind:MSCollectionElementKindCurrentTimeIndicator];
    [self.collectionViewCalendarLayout registerClass:MSCurrentTimeGridline.class forDecorationViewOfKind:MSCollectionElementKindCurrentTimeHorizontalGridline];
    [self.collectionViewCalendarLayout registerClass:MSGridline.class forDecorationViewOfKind:MSCollectionElementKindVerticalGridline];
    [self.collectionViewCalendarLayout registerClass:MSGridline.class forDecorationViewOfKind:MSCollectionElementKindHorizontalGridline];
    [self.collectionViewCalendarLayout registerClass:MSTimeRowHeaderBackground.class forDecorationViewOfKind:MSCollectionElementKindTimeRowHeaderBackground];
    [self.collectionViewCalendarLayout registerClass:MSDayColumnHeaderBackground.class forDecorationViewOfKind:MSCollectionElementKindDayColumnHeaderBackground];
    
    if (_dataArray.count == 0) {
        UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"今天没有安排,点击右上角添加吧!";
        [self.collectionView addSubview:label];
    }

}

-(void)popVc
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)createEvent
{
    BiMATRIXCreateEventViewController* createEventVC = [[BiMATRIXCreateEventViewController alloc]init];
    createEventVC.c_date = [[BmTimeManager sharedInstance]bm_getDateWithTimeString:[NSString stringWithFormat:@"%d-%d-%d",self.year,self.month,self.day] withDateFormat:@"yyyy-MM-dd"];
    createEventVC.addEventDelegate = self;
    [self.navigationController pushViewController:createEventVC animated:YES];
}

-(void)addEvent:(MSEvent *)event
{
    [_dataArray[0] addObject:event];
}

-(BOOL)shouldAutorotate{ return YES;}
-(NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskLandscapeRight;}

- (void)viewDidAppear:(BOOL)animated
{
    
  
    
    [super viewDidAppear:animated];

//    [self.collectionViewCalendarLayout scrollCollectionViewToClosetSectionToCurrentTimeAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController]setTabBarHidden:YES animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[self rdv_tabBarController]setTabBarHidden:NO animated:YES];
    [super viewWillDisappear:animated];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // On iPhone, adjust width of sections on interface rotation. No necessary in horizontal layout (iPad)
    if (self.collectionViewCalendarLayout.sectionLayoutType == MSSectionLayoutTypeVerticalTile) {
        [self.collectionViewCalendarLayout invalidateLayoutCache];
        // These are the only widths that are defined by default. There are more that factor into the overall width.
        self.collectionViewCalendarLayout.sectionWidth = (CGRectGetWidth(self.collectionView.frame) - self.collectionViewCalendarLayout.timeRowHeaderWidth - self.collectionViewCalendarLayout.contentMargin.right);
        [self.collectionView reloadData];
    }
}

#pragma mark - MSCalendarViewController


#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _dataArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_dataArray[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MSEventCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MSEventCellReuseIdentifier forIndexPath:indexPath];

    UITapGestureRecognizer* gr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(log:)];
    gr.numberOfTapsRequired = 2;
    [cell addGestureRecognizer:gr];
    cell.event = _dataArray[indexPath.section][indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    currentIndexPath = indexPath;
    
    if([[_dataArray[indexPath.section][indexPath.row]creatorUserId]integerValue] == [MyUserId integerValue])
    {
        currentSelectedEventTitle = [_dataArray[indexPath.section][indexPath.row] eventTitle];
        self.navigationItem.rightBarButtonItems = @[addEventButtonItem,editEventButtonItem];
    }
    else
    self.navigationItem.rightBarButtonItems = @[addEventButtonItem];
}

-(void)editEvent
{
    [PopoverView showPopoverAtPoint:CGPointMake(SCREEN_WIDTH - 95, -20) inView:self.view withStringArray:@[@"修改",@"删除"] delegate:self];
}

-(void)popoverView:(PopoverView *)popoverView didSelectItemAtIndex:(NSInteger)index
{
    [popoverView dismiss];
    switch (index) {
        case 0:
        {

            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
            NSString *startDateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[[[NSString stringWithFormat:@"%@",[_dataArray[currentIndexPath.section][currentIndexPath.row] eventStartTime]]  substringToIndex:10]integerValue]]];
            NSString *endDateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[[[NSString stringWithFormat:@"%@",[_dataArray[currentIndexPath.section][currentIndexPath.row] eventEndTime]]  substringToIndex:10]integerValue]]];
            
            
            NSMutableArray* array1 = [NSMutableArray arrayWithObjects:@{@"title":[_dataArray[currentIndexPath.section][currentIndexPath.row]eventTitle]},@{@"location":[_dataArray[currentIndexPath.section][currentIndexPath.row]eventPlace]}, nil];
            NSMutableArray* array2 = [NSMutableArray arrayWithObjects:@{@"time":startDateString},@{@"time":endDateString}, nil];
            NSMutableArray* array3 = [NSMutableArray arrayWithObjects:@{@"notification":@"无"},nil];
            BiMATRIXEditEventViewController* editVc = [[BiMATRIXEditEventViewController alloc]init];
            NSMutableArray* data = [NSMutableArray arrayWithObjects:array1,array2,array3, nil];
            editVc.dataArray = data;
            editVc.c_date = [[BmTimeManager sharedInstance]bm_getDateWithTimeString:[NSString stringWithFormat:@"%d-%d-%d",self.year,self.month,self.day] withDateFormat:@"yyyy-MM-dd"];
            editVc.scheduleId = [_dataArray[currentIndexPath.section][currentIndexPath.row]scheduleId];
            [self.navigationController pushViewController:editVc animated:YES];
        }
            break;
            case 1:
        {
            NSMutableDictionary *parameters = [[NSMutableDictionary alloc]initWithDictionary:@{@"myUserId":MyUserId,@"scheduleId":[_dataArray[currentIndexPath.section][currentIndexPath.row]scheduleId],@"pushtype":@"filecast",@"filecastAlert":[NSString stringWithFormat:@"%@%@将标题为%@的日程删除了,请注意查看",[MyStaffName isEqualToString:@"空"]?@"手机号为":@"",[MyStaffName isEqualToString:@"空"]?MyStaffPhone:MyStaffName,currentSelectedEventTitle],@"customerDefine":@"calendar"}];
            
            
           [BmHttpHelper bm_api_deleteCalendarDataWithParameters:parameters success:^(id object) {
               
               [[BiMATRIXCalendarDataSaver sharedDataController].calendarData removeObject:_dataArray[currentIndexPath.section][currentIndexPath.row]];
               [[self.collectionView cellForItemAtIndexPath:currentIndexPath]removeFromSuperview
                ];
               
           }];
        }
            break;
        default:
            break;
    }
}

-(void)log:(UIGestureRecognizer*)sender
{
    [UserDefault setObject:[(MSEventCell*)sender.view event].scheduleId forKey:@"scheduleId"];
//
//    BiMATRIXShareCalendarWithFriendViewController* shareVc = [[BiMATRIXShareCalendarWithFriendViewController alloc]init];
//    shareVc.eventTitle = [(MSEventCell*)sender.view event].eventTitle;
//    [self.navigationController pushViewController:shareVc animated:YES];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view;
    if (kind == MSCollectionElementKindDayColumnHeader) {
        MSDayColumnHeader *dayColumnHeader = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:MSDayColumnHeaderReuseIdentifier forIndexPath:indexPath];
        NSDate *day = [self.collectionViewCalendarLayout dateForDayColumnHeaderAtIndexPath:indexPath];
        NSDate *currentDay = [self currentTimeComponentsForCollectionView:self.collectionView layout:self.collectionViewCalendarLayout];
        dayColumnHeader.day = day;
        dayColumnHeader.currentDay = [[day beginningOfDay] isEqualToDate:[currentDay beginningOfDay]];
        view = dayColumnHeader;
    } else if (kind == MSCollectionElementKindTimeRowHeader) {
        
        MSTimeRowHeader *timeRowHeader = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:MSTimeRowHeaderReuseIdentifier forIndexPath:indexPath];
        timeRowHeader.time = [self.collectionViewCalendarLayout dateForTimeRowHeaderAtIndexPath:indexPath];
        view = timeRowHeader;
        
    }
    return view;
}

#pragma mark - MSCollectionViewCalendarLayout

- (NSDate *)collectionView:(UICollectionView *)collectionView layout:(MSCollectionViewCalendarLayout *)collectionViewCalendarLayout dayForSection:(NSInteger)section
{
    MSEvent *event = [_dataArray[section] firstObject];
    return event.day;
}

- (NSDate *)collectionView:(UICollectionView *)collectionView layout:(MSCollectionViewCalendarLayout *)collectionViewCalendarLayout startTimeForItemAtIndexPath:(NSIndexPath *)indexPath
{
       MSEvent *event = _dataArray[indexPath.section][indexPath.row];
     return event.start;
}

- (NSDate *)collectionView:(UICollectionView *)collectionView layout:(MSCollectionViewCalendarLayout *)collectionViewCalendarLayout endTimeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MSEvent *event = _dataArray[indexPath.section][indexPath.row];
    // Most sports last ~5 hours, and SeatGeek doesn't provide an end time
    if (![event.eventEndTime isEqual:event.eventStartTime]) {
        return [NSDate dateWithTimeIntervalSince1970:[event.eventEndTime longLongValue]/1000];
    }
    else return [event.start dateByAddingTimeInterval:3600*5];
    
}

- (NSDate *)currentTimeComponentsForCollectionView:(UICollectionView *)collectionView layout:(MSCollectionViewCalendarLayout *)collectionViewCalendarLayout
{
    return [NSDate date];
}

@end
